<template>
  <div class="container">
    <!-- 库位列表卡片 -->
    <a-card class="general-card">
      <template #title>库位列表</template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="openAddModal">
            <template #icon><icon-plus /></template>
            新增库位
          </a-button>
          <a-button @click="handleExport">
            <template #icon><icon-export /></template>
            导出
          </a-button>
        </a-space>
      </template>

      <!-- 搜索与操作按钮 -->
      <div class="search-wrapper">
        <a-form :model="searchForm" layout="inline">
          <a-form-item field="warehouse_id" label="所属仓库">
            <a-select 
              v-model="searchForm.warehouse_id" 
              placeholder="请选择所属仓库" 
              allow-clear 
              style="width: 180px"
              @change="filterLocationsByWarehouse"
            >
              <a-option v-for="wh in warehouseList" :key="wh.id" :value="wh.id">{{ wh.name }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="keyword" label="库位编码/名称">
            <a-input v-model="searchForm.keyword" placeholder="搜索库位编码/名称" allow-clear/>
          </a-form-item>
          <a-form-item field="type" label="库位类型">
            <a-select v-model="searchForm.type" placeholder="请选择库位类型" allow-clear style="width: 150px">
              <a-option value="存储区">存储区</a-option>
              <a-option value="收货区">收货区</a-option>
              <a-option value="发货区">发货区</a-option>
              <a-option value="拣货区">拣货区</a-option>
              <a-option value="暂存区">暂存区</a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="status" label="库位状态">
            <a-select v-model="searchForm.status" placeholder="请选择库位状态" allow-clear style="width: 120px">
              <a-option :value="1">启用</a-option>
              <a-option :value="0">禁用</a-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button @click="resetSearch">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <a-table
        :data="locationList"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
        row-key="id"
        stripe
        :scroll="{ x: 760 }"
      >
        <template #empty>
          <div style="text-align: center; padding: 20px 0;">
            <p>暂无库位数据，请先选择一个仓库或添加库位</p>
          </div>
        </template>
        <template #columns>
          <a-table-column title="库位编码" data-index="code" :width="120" fixed="left" />
          <a-table-column title="库位名称" data-index="name" :width="120" :ellipsis="true" tooltip>
            <template #cell="{ record }">
              {{ record.name || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="所属仓库" data-index="warehouse_id" :width="120">
             <template #cell="{ record }">
                {{ getWarehouseName(record.warehouse_id) }}
             </template>
          </a-table-column>
          <a-table-column title="库位类型" data-index="type" :width="90">
            <template #cell="{ record }">
              <a-tag :color="getLocationTypeColor(record.type)">
                {{ getLocationTypeText(record.type) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="容量" data-index="capacity" :width="70">
            <template #cell="{ record }">
              {{ record.capacity !== null && record.capacity !== undefined ? Number(record.capacity) : '-' }}
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="status" :width="80">
            <template #cell="{ record }">
              <a-tag :color="getLocationStatusColor(record.status)">
                {{ getLocationStatusText(record.status) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="160">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="viewLocationInventory(record)">
                  <template #icon><icon-eye /></template>
                  查看库存
                </a-button>
                <a-button type="text" size="small" @click="handleEdit(record)">
                  <template #icon><icon-edit /></template>
                  编辑
                </a-button>
                <a-popconfirm
                  content="确定删除该库位吗？"
                  position="br"
                  @ok="handleDelete(record)"
                >
                  <a-button type="text" status="danger" size="small">
                    <template #icon><icon-delete /></template>
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑库位模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEdit ? '编辑库位' : '新增库位'"
      @ok="handleSubmit"
      @cancel="closeModal"
      :ok-loading="submitLoading"
      unmount-on-close
      width="600px"
    >
      <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
        <a-form-item field="warehouse_id" label="所属仓库" required>
           <a-select v-model="form.warehouse_id" placeholder="请选择所属仓库" :disabled="isEdit" @change="handleWarehouseChange">
             <a-option v-for="wh in warehouseList" :key="wh.id" :value="wh.id">{{ wh.name }}</a-option>
           </a-select>
        </a-form-item>
        <a-form-item field="code" label="库位编码" required>
          <a-input-group>
            <a-input v-model="form.code" placeholder="请输入库位编码" :disabled="isEdit" style="width: calc(100% - 150px)"/>
            <a-button v-if="!isEdit" type="outline" @click="generateLocationCode" style="width: 150px">自动生成编码</a-button>
          </a-input-group>
          <div class="form-item-help-text" v-if="!isEdit">点击"自动生成编码"可创建唯一的库位编码</div>
        </a-form-item>
        <a-form-item field="name" label="库位名称">
          <a-input v-model="form.name" placeholder="请输入库位名称 (可选, 默认同编码)" />
        </a-form-item>
        <a-form-item field="type" label="库位类型" required>
          <a-select v-model="form.type" placeholder="请选择库位类型">
              <a-option value="存储区">存储区</a-option>
              <a-option value="收货区">收货区</a-option>
              <a-option value="发货区">发货区</a-option>
              <a-option value="拣货区">拣货区</a-option>
              <a-option value="暂存区">暂存区</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="capacity" label="容量">
          <a-input-number v-model="form.capacity" placeholder="库位容量" :min="0" style="width: 100%"/>
        </a-form-item>
        <a-form-item field="status" label="库位状态" required>
          <a-radio-group v-model="form.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="remark" label="备注信息">
          <a-textarea v-model="form.remark" placeholder="请输入备注信息" :auto-size="{ minRows: 3, maxRows: 5 }" />
        </a-form-item>
        
        <!-- 隐藏字段区域，供高级用户使用 -->
        <a-collapse :default-active-key="[]">
          <a-collapse-item header="高级选项" key="1">
            <a-row :gutter="16">
              <a-col :span="24">
                <a-form-item field="area" label="区域">
                  <a-input v-model="form.area" placeholder="请输入区域名称 (可选)" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="shelf" label="货架号">
                  <a-input v-model="form.shelf" placeholder="请输入货架号 (可选)" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="level" label="层号">
                  <a-input v-model="form.level" placeholder="请输入层号 (可选)" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-collapse-item>
        </a-collapse>
      </a-form>
    </a-modal>

    <!-- 添加库存查看模态框 -->
    <a-modal
      v-model:visible="inventoryModalVisible"
      title="库位库存信息"
      :footer="false"
      width="900px"
    >
      <div class="inventory-modal-content">
        <div class="inventory-header">
          <div class="location-info">
            <h3>{{ selectedLocation ? selectedLocation.code : '' }} 库位信息</h3>
            <p><strong>所属仓库:</strong> {{ getWarehouseName(selectedLocation?.warehouse_id) }}</p>
            <p><strong>库位类型:</strong> {{ selectedLocation ? getLocationTypeText(selectedLocation.type) : '' }}</p>
            <p><strong>备注:</strong> {{ selectedLocation?.remark || '-' }}</p>
            <p><strong>状态:</strong> <a-tag :color="selectedLocation ? getLocationStatusColor(selectedLocation.status) : ''">
              {{ selectedLocation ? getLocationStatusText(selectedLocation.status) : '' }}
            </a-tag></p>
          </div>
          <div class="inventory-stats">
            <a-statistic title="库存商品种类" :value="locationInventory.length" />
            <a-statistic title="总库存数量" :value="getTotalInventoryQuantity()" />
          </div>
        </div>

        <a-divider />
        
        <a-table
          :data="locationInventory"
          :loading="inventoryLoading"
          :pagination="{ pageSize: 5 }"
          :bordered="false"
          row-key="id"
          :scroll="{ y: 400 }"
          column-resizable
          size="small"
        >
          <template #empty>
            <div style="text-align: center; padding: 20px 0;">
              <p>此库位暂无库存商品</p>
            </div>
          </template>
          <template #columns>
            <a-table-column title="商品编码" data-index="cargo.code" :width="130">
              <template #cell="{ record }">
                {{ record.cargo?.code || '-' }}
              </template>
            </a-table-column>
            <a-table-column title="商品名称" data-index="cargo.name" :width="180">
              <template #cell="{ record }">
                {{ record.cargo?.name || '-' }}
              </template>
            </a-table-column>
            <a-table-column title="规格" data-index="cargo.specification" :width="120">
              <template #cell="{ record }">
                {{ record.cargo?.specification || record.cargo?.spec || record.specification || record.spec || '-' }}
              </template>
            </a-table-column>
            <a-table-column title="库存数量" data-index="quantity" :width="100">
              <template #cell="{ record }">
                <a-statistic :value="record.quantity" :precision="0" />
              </template>
            </a-table-column>
            <a-table-column title="单位" data-index="cargo.unit" :width="80">
              <template #cell="{ record }">
                {{ record.cargo?.unit || '-' }}
              </template>
            </a-table-column>
            <a-table-column title="批次号" data-index="batch_no" :width="120">
              <template #cell="{ record }">
                {{ record.batchNo || record.batch_no || '无批次号' }}
              </template>
            </a-table-column>
            <a-table-column title="生产日期" data-index="production_date" :width="120">
              <template #cell="{ record }">
                {{ record.productionDate || record.production_date ? formatDate(record.productionDate || record.production_date) : '无生产日期' }}
              </template>
            </a-table-column>
            <a-table-column title="过期日期" data-index="expiry_date" :width="120">
              <template #cell="{ record }">
                {{ record.expiryDate || record.expiry_date ? formatDate(record.expiryDate || record.expiry_date) : '无过期日期' }}
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { storeToRefs } from 'pinia';
import { useWarehouseStore } from '@/stores/warehouse';
import { useInventoryStore } from '@/stores/inventory';
import {
  IconPlus,
  IconExport,
  IconSearch,
  IconRefresh,
  IconEye,
  IconEdit,
  IconDelete
} from '@arco-design/web-vue/es/icon';

// --- Pinia Store Integration ---
const warehouseStore = useWarehouseStore();
const inventoryStore = useInventoryStore();
const {
  // Warehouse data for dropdown
  warehouseList,
  // Location state and actions
  locationList,
  locationLoading: loading,
  locationPagination: pagination,
  locationQueryParams: searchForm,
  locationForm: form,
  locationDialogVisible: modalVisible,
} = storeToRefs(warehouseStore);

// --- Component specific state ---
const isEdit = ref(false);
const formRef = ref(null);
const submitLoading = ref(false);

// --- 添加库存查看相关状态 ---
const inventoryModalVisible = ref(false);
const selectedLocation = ref(null);
const locationInventory = ref([]);
const inventoryLoading = ref(false);

// --- 辅助函数 ---
// 获取仓库名称
const getWarehouseName = (warehouseId) => {
  if (!warehouseId) return '-';
  const warehouse = warehouseList.value.find(wh => wh.id === warehouseId);
  return warehouse ? warehouse.name : warehouseId;
};

// 根据状态获取文本和颜色
const getLocationStatusText = (status) => {
  return status === 1 ? '启用' : '禁用';
};

const getLocationStatusColor = (status) => {
  return status === 1 ? 'green' : 'red';
};

// 根据类型获取文本和颜色
const getLocationTypeText = (type) => {
  return type || '-';
};

const getLocationTypeColor = (type) => {
  const colorMap = {
    '存储区': 'blue',
    '收货区': 'green',
    '发货区': 'orangered',
    '拣货区': 'purple',
    '暂存区': 'gold'
  };
  return colorMap[type] || 'gray';
};

// --- 处理搜索和分页事件 ---
const handleSearch = () => {
  warehouseStore.handleLocationSearch();
};

const resetSearch = () => {
  searchForm.value.keyword = '';
  searchForm.value.type = '';
  searchForm.value.status = undefined;
  // 保留仓库ID
  handleSearch();
};

const onPageChange = (page) => {
  warehouseStore.handleLocationPageChange(page);
};

const onPageSizeChange = (pageSize) => {
  warehouseStore.handleLocationSizeChange(pageSize);
};

// --- 处理库位操作事件 ---
const openAddModal = () => {
  isEdit.value = false;
  warehouseStore.handleAddLocation();
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

const handleEdit = (record) => {
  isEdit.value = true;
  warehouseStore.handleEditLocation(record);
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

const handleDelete = (record) => {
  warehouseStore.deleteLocation(record.id)
    .then(() => {
      Message.success('删除库位成功');
      handleSearch();
    })
    .catch(error => {
      console.error('删除库位失败:', error);
      const errMsg = error?.response?.data?.message || error.message || '删除库位失败';
      Message.error(errMsg);
    });
};

const handleExport = () => {
  Message.info('导出功能待实现');
  console.log('Export triggered');
};

const closeModal = () => {
  modalVisible.value = false;
  warehouseStore.resetLocationForm();
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    
    submitLoading.value = true;
    
    const success = await warehouseStore.submitLocation();
    if (success) {
      modalVisible.value = false;
      handleSearch();
    }
  } catch (error) {
    console.error('表单验证失败或提交出错:', error);
  } finally {
    submitLoading.value = false;
  }
};

const filterLocationsByWarehouse = (warehouseId) => {
  searchForm.value.warehouse_id = warehouseId;
  handleSearch();
};

// --- 库位编码生成 ---
const handleWarehouseChange = (warehouseId) => {
  form.value.code = '';
};

const generateLocationCode = () => {
  if (!form.value.warehouse_id) {
    Message.warning('请先选择所属仓库');
    return;
  }
  
  const warehouse = warehouseList.value.find(wh => wh.id === form.value.warehouse_id);
  const warehousePrefix = warehouse ? warehouse.name.substring(0, 1).toUpperCase() : 'L';
  
  const timestamp = Date.now().toString().slice(-6);
  const randomChars = Math.random().toString(36).substring(2, 5).toUpperCase();
  
  form.value.code = `${warehousePrefix}-${timestamp}-${randomChars}`;
};

// --- 查看库位库存 ---
const viewLocationInventory = async (location) => {
  selectedLocation.value = location;
  inventoryModalVisible.value = true;
  inventoryLoading.value = true;
  locationInventory.value = [];
  
  try {
    console.log('查看库位库存:', location);
    // 确保传递正确的locationId参数
    const locationId = location.id;
    
    if (!locationId) {
      Message.warning('库位ID无效，无法查询库存');
      inventoryLoading.value = false;
      return;
    }
    
    // 直接调用获取库位库存的API
    const result = await inventoryStore.getLocationInventory(locationId, {
      page: 1, 
      pageSize: 100
    });
    
    console.log('获取到的库位库存数据:', result);
    
    if (result && (result.list || []).length > 0) {
      // 确保过滤有效的库存记录
      locationInventory.value = result.list.filter(item => 
        item && 
        item.cargo && 
        parseFloat(item.quantity) > 0
      );
      
      if (locationInventory.value.length === 0) {
        console.log('库存数据过滤后为空');
      }
    } else {
      locationInventory.value = [];
      console.log('没有查询到库位库存数据');
    }
  } catch (error) {
    console.error('获取库位库存数据出错:', error);
    Message.error('获取库位库存数据失败');
    locationInventory.value = [];
  } finally {
    inventoryLoading.value = false;
  }
};

// 计算库存总数量
const getTotalInventoryQuantity = () => {
  return locationInventory.value.reduce((total, item) => total + (parseFloat(item.quantity) || 0), 0);
};

// --- 生命周期钩子 ---
onMounted(async () => {
  try {
    console.log('LocationManagement 组件已挂载');
    
    // 获取仓库列表
    await warehouseStore.fetchWarehouses({ page: 1, pageSize: 999 });
    
    // 处理URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const warehouseIdFromUrl = urlParams.get('warehouse_id');
    
    if (warehouseIdFromUrl) {
      searchForm.value.warehouse_id = parseInt(warehouseIdFromUrl);
    } else {
      searchForm.value.warehouse_id = null;
    }
    
    // 获取库位列表
    handleSearch();
  } catch (error) {
    console.error('LocationManagement 初始化失败:', error);
    Message.error('加载数据失败，请刷新页面重试');
  }
});

// --- 监听仓库ID变化 ---
watch(() => searchForm.value.warehouse_id, (newWarehouseId, oldWarehouseId) => {
  if (newWarehouseId !== oldWarehouseId) {
    console.log('仓库ID变更，重新获取库位列表:', newWarehouseId);
    handleSearch();
  }
});

// 表单验证规则
const rules = {
  warehouse_id: [{ required: true, message: '请选择所属仓库' }],
  code: [
    { required: true, message: '请输入库位编码' },
    { maxLength: 50, message: '编码长度不能超过50个字符' }
  ],
  name: [{ maxLength: 100, message: '名称长度不能超过100个字符' }],
  type: [{ required: true, message: '请选择库位类型' }],
  area: [{ maxLength: 50, message: '区域长度不能超过50个字符' }],
  shelf: [{ maxLength: 50, message: '货架号长度不能超过50个字符' }],
  level: [{ maxLength: 50, message: '层号长度不能超过50个字符' }],
  capacity: [
    { type: 'number', message: '容量必须是数字' },
    { validator: (v, cb) => { v !== null && v < 0 ? cb('容量不能为负数') : cb() } }
  ],
  status: [{ required: true, message: '请选择库位状态' }],
  remark: [{ maxLength: 500, message: '备注长度不能超过500个字符' }]
};
</script>

<style lang="less" scoped>
/* 与 WarehouseManagement.vue 保持一致的样式，并增加美化效果 */
.container {
  padding: 0 20px 20px 20px;
}

.search-wrapper {
  margin-bottom: 16px;
}

.general-card {
  margin-top: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  :deep(.arco-card-header) {
    height: 56px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border);
    background-color: #fafafa;
  }
  
  :deep(.arco-table-th) {
    background-color: #f5f7fa;
    font-weight: 600;
  }
  
  :deep(.arco-table-tr:hover) {
    td {
      background-color: rgba(var(--primary-6), 0.05);
    }
  }
  
  :deep(.arco-table-border .arco-table-container) {
    border-top: none;
  }
}

:deep(.arco-form-item) {
  margin-bottom: 16px;
}

:deep(.arco-textarea) {
  resize: none;
}

:deep(.arco-form-item-label) {
  font-weight: 500;
}

:deep(.arco-btn) {
  display: flex;
  align-items: center;

  .arco-icon {
    margin-right: 6px;
  }
}

.form-item-help-text {
  font-size: 12px;
  color: #86909c;
  margin-top: 4px;
}

// 美化自动生成编码按钮
:deep(.arco-input-group) {
  .arco-btn {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    margin-left: -1px;
  }
}

// 改进tag颜色对比度
:deep(.arco-tag) {
  font-weight: 500;
}

// 添加轻微的动画效果
:deep(.arco-table-body) {
  transition: all 0.3s;
}

// 优化空状态显示
:deep(.arco-table-empty) {
  padding: 48px 0;
  
  .arco-empty-image {
    height: 120px;
  }
}

// 添加库位库存模态框样式
.inventory-modal-content {
  .inventory-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
    
    .location-info {
      flex: 1;
      
      h3 {
        margin: 0 0 12px 0;
        font-size: 18px;
        font-weight: 600;
      }
      
      p {
        margin: 6px 0;
        color: var(--color-text-2);
      }
    }
    
    .inventory-stats {
      display: flex;
      gap: 24px;
      
      :deep(.arco-statistic) {
        text-align: center;
        
        .arco-statistic-title {
          color: var(--color-text-3);
        }
        
        .arco-statistic-value {
          color: var(--color-text-1);
          font-weight: 600;
        }
      }
    }
  }
  
  :deep(.arco-table-container) {
    border-radius: 4px;
    overflow: hidden;
  }
  
  :deep(.arco-statistic-value) {
    font-size: 14px !important;
  }
}
</style>